//
//  ZLMainViewController.swift
//  Swift-weibo
//
//  Created by 朱万龙 on 2016/12/9.
//  Copyright © 2016年 zwl. All rights reserved.
//

import UIKit

class ZLMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置tabBar
        setUpChildControllers()
        //tabbarAddButton按钮
        setUpcomposeAddButton()
    }
    /// 使用代码控制设备的方向   需要横屏的时候单独处理.landscape
    /// 设置支持方向后，当前控制器及所有子控制器都会遵守这个协议！
    ///
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    return .portrait
    }
    /// MARK: - 监听方法
    /// fileprivate : 能够保证，方法私有，仅在当前对象中被访问
    /// @objc 允许函数在”运行时“ 通过OC 的消息机制被调用
    @objc fileprivate func composeStatus() {
//
//        print("撰写微博")
//        let vc = UIViewController()
//        vc.view.backgroundColor = UIColor.zl_random()
//        
//        let nav = UINavigationController(rootViewController: vc)
//        present(nav, animated: true, completion: nil)
//        
    }

    //懒加载tabbarAddButton
    fileprivate lazy var composeButton: UIButton = UIButton.zl_button(withImageName: "tabbar_compose_icon_add", backImageName:"tabbar_compose_button", highlightSuffix: "")
}

//extension  类似于OC 中的分类 ，在Swift 中可以用来划分代码块
//可以相近的函数，放在一个extension中
//便于代码维护
//和OC一样不能定义属性

// MARK: - 设置界面
extension ZLMainViewController{

    /// MARK: - 设置所有子控制器
    fileprivate func setUpChildControllers(){
        
        //获取沙盒json路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (path as NSString).appendingPathComponent("Main.json")
        //转Data
        var data = NSData(contentsOfFile: jsonPath)
        //网络下载到沙盒的JSON为空，加载本地JSON
        if data == nil {
            let mainPath = Bundle.main.path(forResource: "Main.json", ofType: nil)
            data = NSData(contentsOfFile: mainPath!)
        }
        
        //使用JSON加载界面
        //1、路径/2、加载Data/3、反序列化转换成数组
        guard let array = try?  JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String: AnyObject]]
            else {
            return
        }
        
        /**
        let array : [[ String : AnyObject]] = [
        ["clsName":"ZLHomeViewController" as AnyObject,
         "imageName":"tabbar_home" as AnyObject,
         "title":"首页" as AnyObject,
         "visitor":["zl_mesage":"关注一些人，回这里看看有什么惊喜","zl_imageName":""] as AnyObject],
        
        ["clsName":"ZLMessageViewController"as AnyObject,
         "imageName":"tabbar_message_center"as AnyObject,
         "title":"消息"as AnyObject,
         "visitor":["zl_mesage":"登录后，别人评论你的微博，发给你的信息，都会在这里收到","zl_imageName":"visitordiscover_image_message"] as AnyObject],
        
        ["clsName":"XXX"as AnyObject,
         "imageName":""as AnyObject,"title":"" as AnyObject],
        
        ["clsName":"ZLDiscaverViewController" as AnyObject,
         "imageName":"tabbar_discover" as AnyObject,
         "title":"发现" as AnyObject,
         "visitor":["zl_mesage":"登陆后，最新、最热微博尽在掌握，不会再与实时潮流擦肩而过","zl_imageName":"visitordiscover_image_message"] as AnyObject],
                                                                   
        ["clsName":"ZLProfileViewController" as AnyObject,
         "imageName":"tabbar_profile" as AnyObject,
         "title":"我" as AnyObject,
         "visitor":["zl_mesage":"登陆后，你的微博、相册、个人资料会显示在这里，展现给别人","zl_imageName":"visitordiscover_image_profile"] as AnyObject]
        ]
        测试数据格式
        (array as NSArray).write(toFile:"/Users/zhuwanlong/Desktop/Dome.plist", atomically: true)
        转换JSON，序列化
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let url = URL(fileURLWithPath: "/Users/zhuwanlong/Desktop/Dome.json")
        (data as NSData).write(toFile: "/Users/zhuwanlong/Desktop/Dome.json", atomically: true)
         **/

        //创建子控制器数组
        var vcArray = [UIViewController]()
        //遍历字典数组，传入controller方法中，创建控制器，添加入vcArray数组中
        for dict in array! {
           vcArray.append(controller(dict: dict))
        }
        viewControllers = vcArray
        
    }
    
    /// MARK: -添加撰写按钮 - （中间加号按钮tabbarButton）
    fileprivate func setUpcomposeAddButton() {
        tabBar.addSubview(composeButton)

        // 计算按钮frame
        let count = CGFloat(childViewControllers.count)
        let zl_tabbar_w = tabBar.bounds.width / count - 1//tabBar按钮中有容错点（1到2个点）
        //insetBy = OC中CGRectInset   正数向内，负数向外
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * zl_tabbar_w, dy: 0)
        //添加监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    /// MARK: - 使用字典创建一个子控制器
    /// - Parameter:  dict: clsNmae imageName title
    /// - Returns:    UIViewController
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        //取得字典内容

        guard let clsName = dict["clsName"],
            let imageName = dict["imageName"],
            let title = dict["title"],
            //改变基类，传递字典信息
            let cls = NSClassFromString(Bundle.main.namespace + "." + (clsName as! String)) as? ZLBaseViewController.Type,
        let visitorInfo = dict["visitor"] as? [String: String]
        else {
            return UIViewController()
        }
        // 创建控制器
        let vc = cls.init()
        vc.title = title as? String
        vc.tabBarItem.image = UIImage(named: imageName as! String)
        vc.tabBarItem.selectedImage = UIImage(named: "\(imageName)_highlighted")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //传递
        vc.visitorInfo = visitorInfo
        //实例化控制器时，会调用push方法将rootVC压栈
        let nav = ZLNavigationController(rootViewController: vc)
        return nav
        
    }
}


